package org.ne.springboot.utils.PaperHandleUtils.FontCheckUtils;

import org.apache.poi.xwpf.usermodel.*;

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Word格式检查报告生成Servlet
 */
public class FormatReportServlet {

    /**
     * 处理GET请求，生成并下载格式检查报告
     */
    public void doGet( Map<String, List<String>> errorMap, OutputStream outputStream) throws Exception {
        // 设置响应头，指定为Word文档格式

        // 如果没有错误数据，使用示例数据
        if (errorMap == null) {
            throw new Exception("请先进行格式检查");
        }
        
        // 生成Word格式的检查报告
        try (XWPFDocument document = new XWPFDocument()) {
            generateReportDocument(document, errorMap);
            document.write(outputStream);
        }
    }

    /**
     * 生成Word报告文档
     */
    private void generateReportDocument(XWPFDocument document, Map<String, List<String>> errorMap) {
        // 添加报告标题
        addTitle(document, "大连民族大学本科毕业设计格式检查报告");
        
        // 添加报告基本信息
        addBasicInfo(document);
        
        // 添加统计信息
        addStatistics(document, errorMap);
        
        // 添加详细错误信息
        addDetailedErrors(document, errorMap);
        
        // 添加改进建议
        addRecommendations(document);
        
        // 添加报告结尾
        addConclusion(document);
    }

    /**
     * 添加报告标题
     */
    private void addTitle(XWPFDocument document, String titleText) {
        XWPFParagraph title = document.createParagraph();
        title.setAlignment(ParagraphAlignment.CENTER);
        
        XWPFRun titleRun = title.createRun();
        titleRun.setText(titleText);
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("黑体");
        
        // 添加空行
        addEmptyLine(document);
    }

    /**
     * 添加基本信息
     */
    private void addBasicInfo(XWPFDocument document) {
        XWPFParagraph info = document.createParagraph();
        
        XWPFRun infoRun = info.createRun();
        infoRun.setText("报告生成时间: " + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()));
        infoRun.setFontSize(12);
        infoRun.setFontFamily("宋体");
        
        addEmptyLine(document);
    }

    /**
     * 添加统计信息
     */
    private void addStatistics(XWPFDocument document, Map<String, List<String>> errorMap) {
        XWPFParagraph statsTitle = document.createParagraph();
        XWPFRun statsTitleRun = statsTitle.createRun();
        statsTitleRun.setText("一、统计信息");
        statsTitleRun.setBold(true);
        statsTitleRun.setFontSize(14);
        statsTitleRun.setFontFamily("黑体");
        
        // 计算统计信息
        int totalErrors = errorMap.values().stream().mapToInt(List::size).sum();
        int affectedParagraphs = errorMap.size();
        
        Map<String, Integer> errorTypeCount = new HashMap<>();
        for (List<String> errors : errorMap.values()) {
            for (String error : errors) {
                String errorType = extractErrorType(error);
                errorTypeCount.put(errorType, errorTypeCount.getOrDefault(errorType, 0) + 1);
            }
        }
        
        // 创建统计表格
        XWPFTable table = document.createTable(4, 2);
        table.setWidth("100%");
        
        // 设置表格样式
        setTableStyle(table);
        
        // 填充表格数据
        setTableCell(table, 0, 0, "总错误数", true);
        setTableCell(table, 0, 1, String.valueOf(totalErrors), false);
        
        setTableCell(table, 1, 0, "受影响段落数", true);
        setTableCell(table, 1, 1, String.valueOf(affectedParagraphs), false);
        
        setTableCell(table, 2, 0, "错误类型分布", true);
        StringBuilder typeDistribution = new StringBuilder();
        errorTypeCount.forEach((type, count) -> {
            typeDistribution.append(type).append(": ").append(count).append("处\n");
        });
        setTableCell(table, 2, 1, typeDistribution.toString(), false);
        
        setTableCell(table, 3, 0, "检查结果", true);
        String result = totalErrors == 0 ? "通过" : "不通过";
        setTableCell(table, 3, 1, result, false);
        
        addEmptyLine(document);
    }

    /**
     * 添加详细错误信息
     */
    private void addDetailedErrors(XWPFDocument document, Map<String, List<String>> errorMap) {
        XWPFParagraph detailsTitle = document.createParagraph();
        XWPFRun detailsTitleRun = detailsTitle.createRun();
        detailsTitleRun.setText("二、详细错误信息");
        detailsTitleRun.setBold(true);
        detailsTitleRun.setFontSize(14);
        detailsTitleRun.setFontFamily("黑体");
        
        addEmptyLine(document);
        
        int index = 1;
        for (Map.Entry<String, List<String>> entry : errorMap.entrySet()) {
            String paragraph = entry.getKey();
            List<String> errors = entry.getValue();
            
            // 添加段落标题
            XWPFParagraph paraTitle = document.createParagraph();
            XWPFRun paraTitleRun = paraTitle.createRun();
            paraTitleRun.setText(index + ". 段落: " + abbreviateText(paragraph, 50));
            paraTitleRun.setBold(true);
            paraTitleRun.setFontSize(12);
            paraTitleRun.setFontFamily("宋体");
            
            // 添加错误列表
            for (String error : errors) {
                XWPFParagraph errorPara = document.createParagraph();
                errorPara.setIndentationLeft(400); // 缩进
                
                XWPFRun errorRun = errorPara.createRun();
                errorRun.setText("• " + error);
                errorRun.setFontSize(11);
                errorRun.setFontFamily("宋体");
                errorRun.setColor("FF0000"); // 红色显示错误
            }
            
            addEmptyLine(document);
            index++;
        }
    }

    /**
     * 添加改进建议
     */
    private void addRecommendations(XWPFDocument document) {
        XWPFParagraph recTitle = document.createParagraph();
        XWPFRun recTitleRun = recTitle.createRun();
        recTitleRun.setText("三、改进建议");
        recTitleRun.setBold(true);
        recTitleRun.setFontSize(14);
        recTitleRun.setFontFamily("黑体");
        
        String[] recommendations = {
            "1. 检查所有标题格式是否符合规范要求（字体、字号、间距等）",
            "2. 确保中英文内容使用正确的字体（中文宋体，英文Times New Roman）",
            "3. 验证段落缩进和行间距设置",
            "4. 检查特殊部分（摘要、目录、参考文献等）的格式要求",
            "5. 确认图表和公式的编号和位置是否正确"
        };
        
        for (String recommendation : recommendations) {
            XWPFParagraph recPara = document.createParagraph();
            recPara.setIndentationLeft(200);
            
            XWPFRun recRun = recPara.createRun();
            recRun.setText(recommendation);
            recRun.setFontSize(11);
            recRun.setFontFamily("宋体");
        }
        
        addEmptyLine(document);
    }

    /**
     * 添加报告结尾
     */
    private void addConclusion(XWPFDocument document) {
        XWPFParagraph conclusion = document.createParagraph();
        
        XWPFRun conclusionRun = conclusion.createRun();
        conclusionRun.setText("注：请根据上述错误信息修改文档格式，确保符合大连民族大学本科毕业设计规范要求。");
        conclusionRun.setItalic(true);
        conclusionRun.setFontSize(11);
        conclusionRun.setFontFamily("宋体");
    }

    /**
     * 设置表格单元格
     */
    private void setTableCell(XWPFTable table, int row, int col, String text, boolean isBold) {
        XWPFTableCell cell = table.getRow(row).getCell(col);
        cell.removeParagraph(0);
        
        XWPFParagraph paragraph = cell.addParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setFontSize(11);
        run.setFontFamily("宋体");
        run.setBold(isBold);
        
        paragraph.setAlignment(ParagraphAlignment.LEFT);
    }

    /**
     * 设置表格样式
     */
    private void setTableStyle(XWPFTable table) {
        // 设置表格边框
        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
        table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
        table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
        table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
        table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
        table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 0, "000000");
    }

    /**
     * 添加空行
     */
    private void addEmptyLine(XWPFDocument document) {
        XWPFParagraph emptyLine = document.createParagraph();
        XWPFRun emptyRun = emptyLine.createRun();
        emptyRun.setText("");
    }

    /**
     * 从错误信息中提取错误类型
     */
    private String extractErrorType(String errorMessage) {
        if (errorMessage.contains("字体")) {
            return "字体错误";
        }
        if (errorMessage.contains("字号")) {
            return "字号错误";
        }
        if (errorMessage.contains("对齐")) {
            return "对齐错误";
        }
        if (errorMessage.contains("间距")) {
            return "间距错误";
        }
        if (errorMessage.contains("缩进")) {
            return "缩进错误";
        }
        if (errorMessage.contains("加粗")) {
            return "加粗状态错误";
        }
        if (errorMessage.contains("行距")) {
            return "行距错误";
        }
        return "其他错误";
    }

    /**
     * 缩写长文本
     */
    private String abbreviateText(String text, int maxLength) {
        if (text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength - 3) + "...";
    }


}